﻿using System.Collections.Generic;
using System.Linq;
using Citi.Import.Util;
using Citi.ResourceConsolidation.Domain.Utils;

namespace Citi.ResourceConsolidation.Domain
{
    public partial class HumanResource
    {
        private const string HumanResouceDepartmentIdColumn = "HR Dept ID";
        private const string HumanResouceDepartmentDescriptionColumn = "HR Department";

        public static readonly List<Definition<HumanResource>> Definitions = new List<Definition<HumanResource>>
            {
                new Definition<HumanResource> { ModelProperty = x => x.Code, MaxLength = 50, Required = true, ColumnName = HumanResouceDepartmentIdColumn, CustomConversionMethod = ValidateCode},
                new Definition<HumanResource> { ModelProperty = x => x.Description, MaxLength = 300, Required = true, ColumnName = HumanResouceDepartmentDescriptionColumn},
            };

        private static object ValidateCode(ref HumanResource model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (string.IsNullOrEmpty(value))
            {
                error = string.Format("The field {0} can not be null", HumanResouceDepartmentIdColumn);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(new HumanResource().SelectAll<HumanResource>).FirstOrDefault(x => x.Code == value);

            if (domain != null)
            {
                model = domain;
                return Conversion.Validation.Validated;
            }

            return value;
        }

        public static void Save(List<HumanResource> humanResources)
        {
            humanResources = humanResources.Distinct(new HumanResourceComparer()).Where(x => x != null && !string.IsNullOrEmpty(x.Code) && x.Id == 0).ToList();

            if (!humanResources.Any()) return;
            humanResources.First().Save(humanResources, 100);

            CacheFacade.Clear(typeof(HumanResource));
            Context.ClearContext();
        }
    }

    public class HumanResourceComparer : IEqualityComparer<HumanResource>
    {
        public bool Equals(HumanResource x, HumanResource y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Id == y.Id && x.Code == y.Code;
        }

        public int GetHashCode(HumanResource item)
        {
            if (ReferenceEquals(item, null)) return 0;

            int hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            int hashId = item.Description == null ? 0 : item.Id.GetHashCode();
            int hashCode = item.Code == null ? 0 : item.Code.GetHashCode();

            return hashDescription ^ hashId ^ hashCode;
        }
    }
}
